package com.example.ssd4.view;

import com.example.ssd4.Main;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegisterDialog {
    private Stage thisStage;
    private VBox vBox;
    private HBox hBox1;
    private GridPane gridPane;
    private HBox hBox2;
    private TextField usernameField;
    private PasswordField passwordField;
    private PasswordField repeatField;
    private PasswordField validaCode;
    private Button cancelBtn;
    private Button confirmBtn;

    private static final String[] IMAGE_PATHS = {
            "/image/bg1_proc.jpg",
            "/image/bg2_proc.jpg",
            "/image/bg3_proc.jpg"
    };

    private static final Duration SLIDE_DURATION = Duration.seconds(3); // 切换图片的持续时间

    private int currentImageIndex = 0;

    private ImageView backgroundImageView;

    public void start(Stage stage) throws Exception {
        //总体布局
        vBox = new VBox();
        hBox1 = new HBox();
        gridPane = new GridPane();
        hBox2 = new HBox();
        // 创建根节点
        StackPane root = new StackPane();

        // 创建背景图片的ImageView
        backgroundImageView = new ImageView();
        root.getChildren().add(backgroundImageView);
        vBox.getChildren().addAll(hBox1,gridPane,hBox2,root);
        vBox.setAlignment(Pos.CENTER);
        // 设置初始背景图片
        setBackgroundImage(IMAGE_PATHS[currentImageIndex]);

        // 创建Timeline对象来切换图片
        Timeline timeline = new Timeline(
                new KeyFrame(SLIDE_DURATION, event -> nextImage())
        );
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.play();


        Scene scene = new Scene(vBox,576,430);
        LoginDialog.addGlobalShortcut(scene);
        initGraphic();
        initAction();
        thisStage = stage;
        thisStage.setScene(scene);
        thisStage.setOnCloseRequest(windowEvent -> {
            close();
        });
        thisStage.show();
    }

    private void nextImage() {
        currentImageIndex = (currentImageIndex + 1) % IMAGE_PATHS.length;
        setBackgroundImage(IMAGE_PATHS[currentImageIndex]);
    }

    private void setBackgroundImage(String imagePath) {
        Image image = new Image(getClass().getResourceAsStream(imagePath));
        backgroundImageView.setImage(image);
    }

    private void initAction() {

        usernameField.setOnAction(actionEvent1 -> {
            passwordField.requestFocus();
            passwordField.selectAll();

        });
        passwordField.setOnAction(actionEvent2 ->{
            repeatField.requestFocus();
            repeatField.selectAll();
        });
        repeatField.setOnAction(actionEvent1 -> {
            validaCode.requestFocus();
            validaCode.selectAll();;
        });
        validaCode.setOnAction(actionEvent1 -> {
            if(confirmValidaCode()&&confirmAccount()&&confirmPassword()) {
                String filename;
                try (BufferedWriter writer = new BufferedWriter(new FileWriter("src\\main\\resources\\data\\user.log", true))) {
                    String data = "User(";
                    if(usernameField.getText().replaceAll(" ","").length()==3) {
                        data += "\"T\",";
                        //创造log文件
                        filename="src\\main\\resources\\data\\teacher\\";
                        filename+=usernameField.getText().replaceAll(" ","");
                        filename+=".log";
                    }
                    else {
                        data+="\"S\",\"";
                        filename="src\\main\\resources\\data\\student\\";
                        filename+=usernameField.getText().replaceAll(" ","");
                        filename+=".log";
                    }
                    data+=usernameField.getText().replaceAll(" ","");
                    data+="\",\"";
                    data+=passwordField.getText().replaceAll(" ","");
                    data+="\")";
                    writer.newLine(); // 换行
                    writer.write(data);
                    try (BufferedWriter writer1 = new BufferedWriter(new FileWriter(filename))) {
                        // 文件创建成功
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                thisStage.close();
            }
        });
        cancelBtn.setOnAction(actionEvent -> {
            thisStage.close();
            LoginDialog loginDialog = new LoginDialog();
            try {
                loginDialog.start(new Stage());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        confirmBtn.setOnAction(actionEvent -> {

            if(confirmValidaCode()&&confirmAccount()&&confirmPassword()) {
                String filename;
                try (BufferedWriter writer = new BufferedWriter(new FileWriter("src\\main\\resources\\data\\user.log", true))) {
                    String data = "User(";
                    if(usernameField.getText().replaceAll(" ","").length()==3) {
                        data += "\"T\",";
                        //创造log文件
                        filename="src\\main\\resources\\data\\teacher\\";
                        filename+=usernameField.getText().replaceAll(" ","");
                        filename+=".log";
                    }
                    else {
                        data+="\"S\",\"";
                        filename="src\\main\\resources\\data\\student\\";
                        filename+=usernameField.getText().replaceAll(" ","");
                        filename+=".log";
                    }
                    data+=usernameField.getText().replaceAll(" ","");
                    data+="\",\"";
                    data+=passwordField.getText().replaceAll(" ","");
                    data+="\")";
                    writer.newLine(); // 换行
                    writer.write(data);
                    try (BufferedWriter writer1 = new BufferedWriter(new FileWriter(filename))) {
                        // 文件创建成功
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                thisStage.close();
            }
        });
    }

    private void initGraphic() {
        //Title
        Insets margin = new Insets(25,0,0,0);
        Text text = new Text("  账号申请");
        text.setFont(Font.font("微软雅黑", FontWeight.BOLD,25));
        Image image = new Image("file:src/main/resources/image/logo3_proc.jpg");
        ImageView imageView = new ImageView(image);
        vBox.setMargin(hBox1,margin);
        hBox1.getChildren().addAll(imageView,text);

        //注册信息
        Label usernameLbl = new Label("Id:");
        usernameLbl.setStyle("-fx-font-size: 15px;");
        Label passwordLbl = new Label("Password:");
        passwordLbl.setStyle("-fx-font-size: 15px;");
        Label repeatLbl   = new Label("Repeat:");
        repeatLbl.setStyle("-fx-font-size: 15px;");
        Label codeLbl     =new Label("Code");
        codeLbl.setStyle("-fx-font-size: 15px;");
        usernameLbl.setMinWidth(80);
        usernameField = new TextField();
        usernameField.setPromptText("请设置用户名");
        passwordField = new PasswordField();
        passwordField.setPromptText("请设置密码");
        repeatField   = new PasswordField();
        repeatField.setPromptText("请重复密码以确认");
        validaCode    =new PasswordField();
        validaCode.setPromptText("validaCode");
        gridPane.add(codeLbl,0,4);
        gridPane.add(validaCode,1,4);
        gridPane.add(usernameLbl,0,1);
        gridPane.add(usernameField,1,1);
        gridPane.add(passwordLbl,0,2);
        gridPane.add(passwordField,1,2);
        gridPane.add(repeatLbl,0,3);
        gridPane.add(repeatField,1,3);
        gridPane.setAlignment(Pos.CENTER);

//        passwordField.setOnMouseEntered(event -> {
//            Node source = (Node) event.getSource();
//            Integer rowIndex = GridPane.getRowIndex(source);
//            if (rowIndex != null) {
//                for (Node child : gridPane.getChildren()) {
//                    Integer childRowIndex = GridPane.getRowIndex(child);
//                    if (childRowIndex != null && childRowIndex.intValue() == rowIndex.intValue()) {
//                        child.setStyle("-fx-background-color: red;");
//                    }
//                }
//            }
//        });

        //Cancel Confirm
        cancelBtn = new Button("取消");
        cancelBtn.setStyle(
                "-fx-pref-width: 100px;-fx-pref-height: 20px;"+
                        "-fx-background-color: #ff2060;"+
                        "-fx-border-radius: 60px;"+
                        "-fx-font-size: 15px;"+
                        "-fx-text-fill: WHITE;"+
                        "-fx-font-weight: bold;");
        confirmBtn = new Button("注册");
        confirmBtn.setStyle(
                "-fx-pref-width: 100px;-fx-pref-height: 20px;"+
                        "-fx-background-color: #40C0FF;"+
                        "-fx-border-radius: 60px;"+
                        "-fx-font-size: 15px;"+
                        "-fx-text-fill: WHITE;"+
                        "-fx-font-weight: bold;");
        hBox2.getChildren().addAll(cancelBtn,confirmBtn);

        //布局调整
        vBox.setPadding(new Insets(20));
        vBox.setSpacing(20);
        gridPane.setVgap(10);
        gridPane.setHgap(10);
        hBox2.setAlignment(Pos.CENTER);
        hBox2.setSpacing(30);


    }
    private boolean confirmAccount(){
        if(!(usernameField.getText().replaceAll(" ","").length()==3||usernameField.getText().replaceAll(" ","").length()==5)) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("");
            alert.setHeaderText("Sorry");
            alert.setContentText("账号格式错误 ");
            alert.showAndWait();
            return false;
        }
        try (BufferedReader reader = new BufferedReader(new FileReader("src\\main\\resources\\data\\user.log"))) {
            // 读取文件内容
            String line;
            while((line = reader.readLine()) != null) {
                String regex = "\"([^\"]*)\"";
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(line);
                List<String> data=new ArrayList<>();
                while (matcher.find()) {
                    data.add(matcher.group(1));
                }
                if(usernameField.getText().replaceAll(" ","").equals(data.get(1))){
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("");
                    alert.setHeaderText("Sorry");
                    alert.setContentText("账号已存在");
                    alert.showAndWait();
                    return false;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }
    private boolean confirmPassword(){
        if(!passwordField.getText().replaceAll(" ","").equals(repeatField.getText().replaceAll(" ",""))){
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("");
            alert.setHeaderText("Sorry");
            alert.setContentText("两次密码不一致");
            alert.showAndWait();
            return false;
        }
        else if(passwordField.getText().length()<=6){
            //追加密码安全等级判断
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("");
            alert.setHeaderText("Sorry");
            alert.setContentText("密码长度过短");
            alert.showAndWait();
            return false;
        }
        return true;
    }
    private boolean confirmValidaCode(){
        if(validaCode.getText().replaceAll(" ","").equals("CSU"))
            return true;
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("");
        alert.setHeaderText("Sorry");
        alert.setContentText("激活码错误");
        alert.showAndWait();
        return false;
    }
    public void close(){
        Main.loginDialog.setRegisterDialogNull();
        thisStage.close();
    }
    public void setTop(){
        thisStage.setAlwaysOnTop(true);
    }
    public void setNotTop(){
        thisStage.setAlwaysOnTop(false);
    }
}
